12. Exercise: Touch Events
22 12 AAK TouchEvent Intro SC V2
Android Developer Documentation
Exercise
In this exercise you are going to use the onTouchEvent() method to respond to motion on the display.
- In
MyCanvasView, override theonTouchEvent()method to cache thexandycoordinates of the passed inevent. Then use awhenexpression to handle motion events for touching down on the screen, moving on the screen, and releasing touch on the screen. These are the events of interest for drawing a line on the screen. For each event type, call a utility method, as shown in the code below. See the MotionEvent class documentation for a full list of touch events.
override fun onTouchEvent(event: MotionEvent): Boolean {
motionTouchEventX = event.x
motionTouchEventY = event.y
when (event.action) {
MotionEvent.ACTION_DOWN -> touchStart()
MotionEvent.ACTION_MOVE -> touchMove()
MotionEvent.ACTION_UP -> touchUp()
}
return true
}
- At the class level, add the missing
motionTouchEventXandmotionTouchEventYvariables for caching the x and y coordinates of the current touch event (theMotionEventcoordinates). Initialize them to0f.
private var motionTouchEventX = 0f
private var motionTouchEventY = 0f
- Create stubs for the three functions
touchStart(),touchMove(), andtouchUp().
private fun touchStart() {}
private fun touchMove() {}
private fun touchUp() {}
- Your code should build and run, but you won't see any different from the colored background yet.